<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="服务项目名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入服务项目名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商户名称" prop="merchantName">
        <el-select
          v-model="queryParams.merchantName"
          placeholder="请选择商户名称"
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="item in merchantOptions"
            :key="item.id"
            :label="item.name"
            :value="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="原价" prop="originalPrice">
        <el-input
          v-model="queryParams.originalPrice"
          placeholder="请输入原价"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="折扣价" prop="presentPrice">
        <el-input
          v-model="queryParams.presentPrice"
          placeholder="请输入折扣价"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="服务介绍" prop="introduction">
        <el-input
          v-model="queryParams.introduction"
          placeholder="请输入服务介绍"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="删除状态" prop="deleted">
        <el-input
          v-model="queryParams.deleted"
          placeholder="请输入删除状态"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:details:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:details:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:details:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:details:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="detailsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键id" align="center" prop="id" />
      <el-table-column label="服务项目名" align="center" prop="name" />
<!--      <el-table-column label="商户id" align="center" prop="mId" />-->
      <el-table-column label="商户名称" align="center" prop="merchantName" />
<!--      <el-table-column label="服务类别" align="center" prop="typeId" />-->
      <el-table-column label="服务类别" align="center" prop="typeName"/>
      <el-table-column label="原价" align="center" prop="originalPrice" />
      <el-table-column label="折扣价" align="center" prop="presentPrice" />
      <el-table-column label="服务介绍" align="center" prop="introduction" />
<!--      <el-table-column label="服务图片" align="center" prop="img" />-->
      <el-table-column label="删除状态" align="center" prop="deleted" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:details:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:details:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改服务详情对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="detailsRef" :model="form" :rules="rules" label-width="80px">
         <el-form-item label="商户名称" prop="mId">
           <el-select v-model="form.mId" placeholder="请选择商户名称" @change="handleMerchantChange">
             <el-option
               v-for="item in merchantOptions"
               :key="item.id"
               :label="item.name"
               :value="item.id"
             />
           </el-select>
         </el-form-item>
        <el-form-item label="服务类别" prop="typeId">
          <el-select v-model="form.typeId" placeholder="请选择服务类别" @change="handleTypeChange">
            <el-option
              v-for="item in typeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="服务项目名" prop="name">
          <el-select v-model="form.name" placeholder="请先选择商户和服务类别" :disabled="!form.mId || !form.typeId" @change="handleProjectNameChange">
            <el-option
                v-for="item in filteredProjects"
                :key="item.id"
                :label="item.name"
                :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="原价" prop="originalPrice">
          <el-input v-model="form.originalPrice" placeholder="请输入原价" />
        </el-form-item>
        <el-form-item label="折扣价" prop="presentPrice">
          <el-input v-model="form.presentPrice" placeholder="请输入折扣价" />
        </el-form-item>
        <el-form-item label="服务介绍" prop="introduction">
          <el-input v-model="form.introduction" placeholder="请输入服务介绍" />
        </el-form-item>
<!--        <el-form-item label="服务图片" prop="img">-->
<!--          <el-input v-model="form.img" placeholder="请输入服务图片" />-->
<!--        </el-form-item>-->
        <el-form-item label="删除状态" prop="deleted">
          <el-input v-model="form.deleted" placeholder="请输入删除状态" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Details">
import { listDetails, getDetails, delDetails, addDetails, updateDetails } from "@/api/system/details"
import { listType,getType } from "@/api/system/type.js"
import { listMerchant, getMerchant} from "@/api/system/merchant.js"
import { getProject,listProjectByStId} from "@/api/system/project.js";

const { proxy } = getCurrentInstance()

const detailsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const typeName = ref([])
const typeOptions = ref([])
const merchantOptions = ref([])
const filteredProjects = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    mId: null,
    merchantName: null,
    typeId: null,
    originalPrice: null,
    presentPrice: null,
    introduction: null,
    img: null,
    deleted: null
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询服务详情列表 */
async function getList() {
  loading.value = true;
  
  // 先获取商户选项和服务类别选项
  await Promise.all([
    listMerchant().then(response => {
      merchantOptions.value = response.rows || [];
    }),
    listType().then(response => {
      typeOptions.value = response.rows || [];
    })
  ]);

  // 构建查询参数，移除merchantName（因为后端不支持）
  const queryParamsForBackend = { ...queryParams.value };
  delete queryParamsForBackend.merchantName;
  
  // 如果指定了商户名称，需要先找到对应的商户ID
  if (queryParams.value.merchantName) {
    const selectedMerchant = merchantOptions.value.find(
      merchant => merchant.name === queryParams.value.merchantName
    );
    if (selectedMerchant) {
      queryParamsForBackend.mId = selectedMerchant.id;
    }
  }
  
  const response = await listDetails(queryParamsForBackend);
  let filteredList = response.rows;

  // 为每个项目获取服务类别名称和商户名称
  for (const item of filteredList) {
    try {
      const typeRes = await getType(item.typeId);
      item.typeName = typeRes.data.name;
    } catch (error) {
      console.error('获取服务类别名称失败:', error);
      item.typeName = '未知';
    }
    
    try {
      const merchantRes = await getMerchant(item.mId);
      item.merchantName = merchantRes.data.name;
    } catch (error) {
      console.error('获取商户名称失败:', error);
      item.merchantName = '未知';
    }
  }

  detailsList.value = filteredList;
  total.value = response.total; // 使用后端返回的总数
  loading.value = false;
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

async function handleTypeChange() {
  // 清空服务项目选择、价格和服务介绍
  form.value.name = null;
  form.value.originalPrice = null;
  form.value.presentPrice = null;
  form.value.introduction = null;
  
  if (!form.value.typeId) {
    filteredProjects.value = [];
    return;
  }
  
  // 如果没有选择商户，提示用户先选择商户
  if (!form.value.mId) {
    proxy.$modal.msgWarning("请先选择商户");
    form.value.typeId = null;
    return;
  }
  
  loading.value = true;
  console.log("typeId:", form.value.typeId)
  console.log("mId:", form.value.mId)
  const response = await listProjectByStId(form.value.typeId);
  
  // 获取该商户下该类型已存在的项目名称
  const existingProjects = await getExistingProjects(form.value.mId, form.value.typeId);
  console.log('已存在的项目:', existingProjects);
  console.log('所有可选项目:', response);
  
  // 过滤掉已存在的项目
  filteredProjects.value = response.filter(project => 
    !existingProjects.includes(project.name)
  ) || [];
  
  console.log('过滤后的项目:', filteredProjects.value);
  
  loading.value = false;
}

// 获取已存在的项目名称
async function getExistingProjects(mId, typeId) {
  if (!mId || !typeId) {
    return [];
  }
  
  try {
    // 查询该商户下该类型已存在的项目，设置较大的页面大小以获取所有数据
    const queryParams = {
      mId: mId,
      typeId: typeId,
      pageNum: 1,
      pageSize: 1000  // 设置较大的页面大小以获取所有数据
    };
    const response = await listDetails(queryParams);
    return response.rows.map(item => item.name);
  } catch (error) {
    console.error('获取已存在项目失败:', error);
    return [];
  }
}

// 商户选择变化处理
async function handleMerchantChange() {
  // 清空服务项目选择、价格和服务介绍
  form.value.name = null;
  form.value.originalPrice = null;
  form.value.presentPrice = null;
  form.value.introduction = null;
  filteredProjects.value = [];
  
  // 如果已经选择了服务类别，重新过滤项目
  if (form.value.typeId) {
    await handleTypeChange();
  }
}

// 服务项目名称变化处理
function handleProjectNameChange() {
  if (!form.value.name) {
    // 清空价格字段和服务介绍
    form.value.originalPrice = null;
    form.value.presentPrice = null;
    form.value.introduction = null;
    return;
  }
  
  // 从filteredProjects中找到选中的项目
  const selectedProject = filteredProjects.value.find(project => project.name === form.value.name);
  
  if (selectedProject) {
    // 自动填充原价、折扣价和服务介绍
    form.value.originalPrice = selectedProject.oldPrice;
    form.value.presentPrice = selectedProject.newPrice;
    form.value.introduction = selectedProject.serviceIntroduce;
  }
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    mId: null,
    typeId: null,
    originalPrice: null,
    presentPrice: null,
    introduction: null,
    img: null,
    deleted: null
  }

  filteredProjects.value = [];
  proxy.resetForm("detailsRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加服务详情"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getDetails(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改服务详情"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["detailsRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateDetails(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addDetails(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除服务详情编号为"' + _ids + '"的数据项？').then(function() {
    return delDetails(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/details/export', {
    ...queryParams.value
  }, `details_${new Date().getTime()}.xlsx`)
}

getList()
</script>
